package com.hyg.lib_music.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_music.R;
import com.hyg.lib_music.databinding.FragmentJieyaRecommendBinding;
import com.hyg.lib_music.modle.MusicTesttingResultData;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.ui.activity.MusicMainActivity;
import com.hyg.lib_music.ui.activity.MusicPlayingDetailActivity;
import com.hyg.lib_music.ui.activity.PlayingListActivity;
import com.hyg.lib_music.ui.activity.TesttingXinliActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class RecommendJieyaFragment extends Fragment {
    FragmentJieyaRecommendBinding binding;
    MusicMainActivity activity;
    List<RecommedMusicData.DataDTO> list;
    int type = 3, sleepMusicType = 0;
    String test_result="";
    ArrayList<Music> music_list=new ArrayList<>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentJieyaRecommendBinding.inflate(inflater, container, false);
        EventBus.getDefault().register(this);
        init();
        return binding.getRoot();
    }

    public void init() {
        initView();
        initData();
    }

    public void initView() {
        activity = (MusicMainActivity) getActivity();
        Glide.with(getActivity()).load(R.mipmap.jieya_music_icon).into(binding.itemControl1.ivControlImage);
//        binding.itemControl1.cvRoot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (music_list.size() > 0) {
//                    Intent intent = new Intent(getActivity(), PlayingListActivity.class);
//                    intent.putParcelableArrayListExtra("data", music_list);
//                    startActivity(intent);
//                } else {
//                    Toast.makeText(activity, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        binding.itemControl1.lnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (music_list != null && music_list.size() > 0 && MusicMainActivity.serviceBinder != null) {
                    MusicMainActivity.result_type=test_result;
                    MusicMainActivity.serviceBinder.setImagePath(R.mipmap.jieya_music_icon);
                    startActivity(new Intent(getActivity(), MusicPlayingDetailActivity.class));
                    MusicMainActivity.serviceBinder.addPlayList(music_list, music_list.get(0));
                }else {
                    Toast.makeText(activity, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        binding.noRecommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TesttingXinliActivity.class);
                startActivity(intent);
            }
        });
        binding.btnRetest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TesttingXinliActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        CommonHttpUtil.getHealthMusic(getActivity(), type, sleepMusicType, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.ErrorDialog("服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse Jieya: " + result);
                parseData(result);
            }
        });
        getTesttingResultInfo();
    }


    public void parseData(String data) {
        RecommedMusicData musicData = JSONObject.parseObject(data, RecommedMusicData.class);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (musicData.getCode() == 200) {
                    list = musicData.getData();
                    long sum=0;
                    for(RecommedMusicData.DataDTO dataDTO:list){
                        sum+=dataDTO.getMusicDuration();
                    }
                    binding.itemControl1.tvControlIntro.setText((sum/60+1)+"min");
                    music_list.clear();
                    for (RecommedMusicData.DataDTO dataDTO : list) {
                        music_list.add( new Music(dataDTO.getId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                                dataDTO.getRegion(), dataDTO.getMusicUrl(), (dataDTO.getFavorite()==1),
                                3,sleepMusicType, test_result,
                                false,false,false));
                    }
                } else {
                    activity.ErrorDialog(musicData.getMessage());
                }
            }
        });
    }


    public void getTesttingResultInfo() {
        CommonHttpUtil.getMusicTestResult(getActivity(), 3, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse:result  33333==== " + result);
                MusicTesttingResultData data = JSONObject.parseObject(result, MusicTesttingResultData.class);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (data.code == 200) {
                            long days = getPastDays(data.data.getUpdateTime());
                            test_result = data.data.getResult();
                            binding.lnRetest.setVisibility(View.VISIBLE);
                            binding.noRecommend.setVisibility(View.GONE);
                            binding.tvDaysPast.setText(days + "");
                            binding.itemControl1.tvControlTitle.setText("解压定制方案");
                        } else {
                            binding.lnRetest.setVisibility(View.GONE);
                            binding.noRecommend.setVisibility(View.VISIBLE);
                            binding.itemControl1.tvControlTitle.setText("解压试听方案");
                        }
                    }
                });
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.i("lgb", "onResume: jieya");
    }

    @SuppressLint("NewApi")
    public long getPastDays(String data) {
        long days = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(data);
            long titmesss = date.getTime();
            long currenttimes = System.currentTimeMillis();
            days = (currenttimes - titmesss) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    @Subscribe
    public void onEvent(EventBusMessage message) {
        Log.i("lgb", "onEvent:jieya "+message.getmessage());
        //接收以及处理数据
        if(message.getmessage().equals("updateXLdata")){
            initData();
        }else if(message.getmessage().equals(Constants.Add_Favorite)){
            for(Music music:music_list){
               if( music.id==message.getMusicId()){
                   music.isFav=true;
               }
            }
        }else if(message.getmessage().equals(Constants.Cancel_Favorite)){
            for(Music music:music_list){
                if( music.id==message.getMusicId()){
                    music.isFav=false;
                }
            }
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}